package com.fang.controller;


import com.fang.pojo.JsonResult;
import com.fang.pojo.User;
import com.fang.service.UserService;
import com.fang.utils.CreateImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@RestController
@CrossOrigin
@Slf4j      // 日志对象
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*
    * 用户登录
    * */
    @PostMapping("/login")
    public JsonResult login(@RequestBody User user, String code, String key, HttpServletRequest request) {
        log.info("接收到的user对象：" + user);
        log.info("用户输入的验证码：" + code);
        String keCode = (String) request.getServletContext().getAttribute(key);
        log.info("生成的验证码：" + keCode);
        JsonResult jsonResult = new JsonResult();
        try {
            if (code.equalsIgnoreCase(keCode)) {
                User userDB = userService.login(user);
                // 登录成功之后保存用户的标记
                request.getServletContext().setAttribute(String.valueOf(userDB.getId()), userDB);
                jsonResult.setState(true).setMsg("登录成功").setUserId(String.valueOf(userDB.getId()));
            } else {
                throw new RuntimeException("验证码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(false).setMsg(e.getMessage());
        }
        return jsonResult;
    }

    /*
    * 用户注册
    * */
    @PostMapping("/register")
    public JsonResult register(@RequestBody User user, String code, String key, HttpServletRequest request) {
        log.info("接收到的验证码：" + code);  // 表单提交的验证码
        log.info("接收到的user对象：" + user);
        JsonResult jsonResult = new JsonResult();
        String keyCode = (String) request.getServletContext().getAttribute(key); // 获取生成的验证码
        log.info("生成的验证码：" + keyCode);
        try {
            // 忽视大小写比较
            if (code.equalsIgnoreCase(keyCode)) { // 验证码正确
                userService.register(user);
                jsonResult.setState(true).setMsg("注册成功");
            } else { // 验证码错误
                throw new RuntimeException("验证码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(false).setMsg(e.getMessage());
        }
        return jsonResult;
    }

    /*
    * 生成验证码
    * */
    @GetMapping("/getImage")
    public Map<String, String> getImage(HttpServletRequest request) throws IOException {
        HashMap<String, String> result = new HashMap<>();
        CreateImageUtils createImageUtils = new CreateImageUtils();
        // 获取验证码
        String code = createImageUtils.getCode();
        // 验证码存入session
        // 为每一个code生成唯一的key
        String key = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        request.getServletContext().setAttribute(key, code);
        // 生成图片
        BufferedImage buffImg = createImageUtils.getBuffImg();
        // 进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(buffImg, "png", bos);
        // Base64utils Spring提供
        String string = Base64Utils.encodeToString(bos.toByteArray());
        result.put("key", key);
        result.put("image", string);
        return result;
    }
}
